﻿using System;
using System.IO;
using System.Linq;
using System.Threading;
using Antlr.Runtime;
using Compiler.Helpers;
using Compiler.Helpers.ANTLR;

namespace Compiler
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                var filePath = string.Empty;
                if (args.Length >= 2)
                {
                    if (args.ElementAt(0) == ArgType.File.GetParamString())
                    {
                        filePath = args.ElementAt(1);
                    } 
                }

                var lexer = new ZZXLexer(new ANTLRFileStream(filePath));
                var commonTokenStream = new CommonTokenStream(lexer);

                var parser = new ZZXParser(commonTokenStream);
                var log = new LogStringWriterDecorator(Common.Logging.LogManager.GetCurrentClassLogger());

                if (args.Length == 3)
                {
                    if (args.ElementAt(2) == ArgType.LogSource.GetParamString())
                    {
                        var reader = File.OpenText(filePath);
                        log.SourceCode = reader;
                        log.EnableLogSource = true;
                    }
                }

                parser.TraceDestination = log;
                parser.program();
                Console.WriteLine("Compilation finshed. Number of syntax errors: " + parser.NumberOfSyntaxErrors + ".");
                log.TraceLog();
            }
            else
            {
                Console.WriteLine("Please, run this tool from the command line with the syntax showed below.");
                Console.WriteLine("Compiler.exe -file [filePath]");
                Console.WriteLine("You can also specify '-logs' parameter at the of passed args for the source logging.");
                Console.WriteLine();
                Console.WriteLine("---------------------------------------------------");
                Console.WriteLine("Author: Dima Martovoi");
                Console.WriteLine("email: dimamartovoi@hotmail.com");
                Console.WriteLine("---------------------------------------------------");

                Thread.Sleep(4000);
            }
        }
    }
}
